<template>
  <div class="no-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item>轮播管理</el-breadcrumb-item>
            </el-breadcrumb></span
          >
        </div>
      </template>
      <div>
        <el-button
          type="primary"
          size="small"
          @click="(dialogVisible = true), (type = 'add')"
          >添加轮播</el-button
        >
        <el-button type="danger" size="small" @click="deletes"
          >批量删除</el-button
        >
        <el-select
          v-model="enable"
          clearable
          size="small"
          style="width: 150px; margin-left: 10px"
          placeholder="请选择是否轮播"
        >
          <el-option label="是" :value="1"> </el-option>
          <el-option label="否" :value="0"> </el-option>
        </el-select>
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="searchKey"
          size="small"
          style="width: 250px; margin-left: 10px"
        >
        </el-input>
      </div>
      <el-table
        ref="multipleTable"
        :data="NoticeList"
        tooltip-effect="dark"
        v-loading="loading"
        :stripe="true"
        :height="maxHeight"
        style="width: 100%; top: 15px"
        @selection-change="accountSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left">
        </el-table-column>

        <el-table-column
          label="标题"
          width="120"
          fixed="left"
          show-overflow-tooltip
        >
          <template #default="scope">{{ scope.row.title }}</template>
        </el-table-column>
        <el-table-column label="是否正在轮播" width="120" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.enableValue }}</template>
        </el-table-column>
        <el-table-column label="地址" width="200" show-overflow-tooltip
          ><template #default="scope">
            <el-link type="primary" target="_blank" :href="scope.row.url">{{
              scope.row.url
            }}</el-link>
          </template>
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="创建时间"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="最近更新"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button type="primary" @click="edit(scope.row.id)" size="mini"
              >编辑</el-button
            >
            <el-popconfirm
              confirmButtonText="确定"
              cancelButtonText="取消"
              icon="el-icon-info"
              cancelButtonType="danger"
              iconColor="red"
              title="确定删除该公告信息吗？"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" size="mini">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 30px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[15, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :disabled="loading"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      :title="type == 'add' ? '添加轮播' : '编辑轮播'"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="notice" label-width="80px" ref="saveRef" :rules="Rules">
        <el-form-item label="轮播名称" prop="title">
          <el-input v-model="notice.title"></el-input>
        </el-form-item>
        <el-form-item label="链接地址" prop="url">
          <el-input v-model="notice.url"></el-input>
        </el-form-item>
        <el-form-item label="是否轮播" prop="enable">
          <el-select v-model="notice.enable" placeholder="请选择是否轮播">
            <el-option label="是" :value="0"></el-option>
            <el-option label="否" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="picture">
          <el-upload
            class="upload-demo"
            list-type="picture"
            action=""
            :http-request="upFile"
            :limit="1"
            :on-exceed="onExceed"
            :on-remove="onRemove"
            :fileList="fileList"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 文件，且不超过 500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, watch, ref, unref } from "vue";
import { Notice, CarouselService } from "@/api/carousel";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { BaseUrl } from "@/utils/request";
export default {
  name: "Carousel",
  setup() {
    const noticeList: Notice[] = [];
    const saveRef = ref();
    const handleSizeChange = (size: number) => {
      data.pageSize = size;
    };
    const handleCurrentChange = (page: number) => {
      data.currentPage = page;
    };
    const accountSelectionChange = (selectd: Notice[]) => {
      data.selectdIds = [];
      selectd.forEach((i: Notice) => {
        // @ts-ignore
        data.selectdIds.push(i.id);
      });
    };
    const handleDelete = (id: number) => {
      CarouselService.delete([id]).then(() => {
        data.currentPage = 1;
        if (data.currentPage == 1) {
          list();
        }
      });
    };
    const deletes = () => {
      if (data.selectdIds.length == 0) {
        ElMessage({
          showClose: true,
          message: "至少选择一条",
          type: "error",
        });
        return;
      }
      ElMessageBox.confirm("此操作将永久删除这些轮播, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          CarouselService.delete(data.selectdIds).then(() => {
            data.currentPage = 1;
            if (data.currentPage == 1) {
              ElMessage({
                showClose: true,
                message: "删除成功",
                type: "success",
              });
              list();
            }
          });
        })
        .catch(() => {});
    };
    const handleClose = () => {
      data.dialogVisible = false;
      // @ts-ignore
      data.notice = {};
      data.fileList = [];
    };
    const save = () => {
      const saveRefd = unref(saveRef);
      if (!saveRefd) return;
      saveRefd.validate((valid: Boolean) => {
        if (valid) {
          data.dialogVisible = false;
          if (data.type == "add") {
            CarouselService.save(data.notice).then(() => {
              list();
              // @ts-ignore
              data.notice = {};
            });
          } else {
            CarouselService.edit(data.notice).then(() => {
              list();
              // @ts-ignore
              data.notice = {};
            });
          }
        }
      });
    };
    const edit = (id: number) => {
      data.type = "edit";
      CarouselService.get(id).then((res) => {
        //console.log(res.data);
        const enable = res.data.enableValue == "是" ? 0 : 1;
        data.notice = res.data;
        data.notice.enable = enable;
        data.fileList = [
          {
            // @ts-ignore
            url: `${BaseUrl}${data.notice.picture}`,
          },
        ];
        data.dialogVisible = true;
      });
    };
    const isImg = (ext: string): boolean => {
      return ["png", "jpg", "jpeg", "bmp"].indexOf(ext.split(".")[1]) !== -1;
    };
    // @ts-ignore
    const notice: Notice = {};
    let data = reactive({
      maxHeight: document.documentElement.clientHeight - 280,
      searchKey: "",
      NoticeList: noticeList,
      notice: notice,
      loading: false,
      total: 0,
      currentPage: 1,
      type: "add",
      pageSize: 15,
      enable: null,
      dialogVisible: false,
      selectdIds: [],
      handleSizeChange: handleSizeChange,
      handleCurrentChange: handleCurrentChange,
      accountSelectionChange: accountSelectionChange,
      handleDelete: handleDelete,
      handleClose: handleClose,
      save: save,
      edit: edit,
      deletes: deletes,
      fileList: [],
      Rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        url: [{ required: true, message: "请输入地址", trigger: "blur" }],
        enable: [
          {
            required: true,
            message: "请选择是否轮播",
            trigger: "change",
          },
        ],
        picture: [{ required: true, message: "请上传轮播图", trigger: "blur" }],
      },
      beforeUpload(param: any) {
        if (isImg(param.name)) {
          return true;
        } else {
          ElNotification({
            showClose: true,
            title: "遇到错误",
            message: "请先检查文件格式，文件格式只能是图片",
            type: "error",
          });
          return false;
        }
      },
      onExceed() {
        ElNotification({
          showClose: true,
          title: "遇到错误",
          message: "请先移除已上传的文件再进行上传",
          type: "error",
        });
      },
      onRemove() {
        data.notice.picture = "";
      },
      upFile(param: any) {
        let fileObject = param.file;
        if (isImg(fileObject.name)) {
          let formData = new FormData();
          formData.append("file", fileObject);
          //@ts-ignore
          CarouselService.upFile(formData).then((res) => {
            if (res.code == 200) {
              data.notice.picture = res.data;
              data.fileList = [
                {
                  // @ts-ignore
                  name: fileObject.name,
                  // @ts-ignore
                  url: `${BaseUrl}${data.active.picture}`,
                },
              ];
              ElMessage({
                showClose: true,
                message: "上传成功",
                type: "success",
              });
            } else {
              data.fileList = [];
            }
          });
        }
      },
    });
    const getHeight = () => {
      data.maxHeight = document.documentElement.clientHeight - 280;
    };

    const list = () => {
      data.loading = true;
      CarouselService.list({
        page: data.currentPage,
        size: data.pageSize,
        keyword: data.searchKey,
        enable: data.enable,
        // @ts-ignore
      }).then((res) => {
        const { total } = res.data;
        data.NoticeList = res.data.data;
        data.total = total;
        data.loading = false;
      });
    };
    list();
    watch(
      () => data.searchKey,
      (newValue, oldVlaue) => {
        data.searchKey = newValue;
        // @ts-ignore
        list();
      }
    );
    watch(
      () => data.enable,
      (newValue, oldVlaue) => {
        data.enable = newValue;
        // @ts-ignore
        list();
      }
    );
    watch(
      () => data.pageSize,
      (newValue, oldVlaue) => {
        data.pageSize = newValue;
        // @ts-ignore
        list();
      }
    );
    watch(
      () => data.currentPage,
      (newValue, oldVlaue) => {
        data.currentPage = newValue;
        // @ts-ignore
        list();
      }
    );
    window.addEventListener("resize", getHeight, false);
    return {
      ...toRefs(data),
      saveRef,
    };
  },
};
</script>

<style lang="less" scoped>
.el-divider--horizontal {
  margin: 15px 0;
}
.el-dialog__body {
  padding: 30px 30px !important;
}
</style>

<style lang="less">
.no-container {
  .el-dialog__body {
    padding: 30px 30px !important;
  }
  .el-dialog {
    margin-top: 10vh !important;
  }
}
</style>